/**
 * @file drv_adc.c
 * @brief HAL CUBEMX DRIVER
 * 
 * @author dalin (dalin@open-robot.com)
 * @version 1.0
 * @date 2023-05-10
 * 
 * @copyright Copyright (c) 2023  Open Robot Tech.co, Ltd
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2023-05-10 <td>1.0     <td>dalin     <td>内容
 * </table>
 */

#include "drv_adc.h"

#ifdef USE_ADC_DRIVER
#include "mlog.h"
#include "adc.h"

__weak ADC_HandleTypeDef hadc1;
__weak ADC_HandleTypeDef hadc2;
__weak ADC_HandleTypeDef hadc3;


/**
 * @brief Get the adc handle object
 * 
 * @param  adcx             : adcx
 * 
 * @return ADC_HandleTypeDef* 
 */
static ADC_HandleTypeDef * get_adc_handle(adcNumber_e adcx)
{
    ADC_HandleTypeDef *handle = NULL;

    switch (adcx)
    {
    case DRV_ADC_1:
        handle = &hadc1;
        break;
    case DRV_ADC_2:
        handle = &hadc2;
        break;
    case DRV_ADC_3:
        handle = &hadc3;
        break;
    
    default:
        log_error("adc %d error", adcx);
        break;
    }
    return handle;
}


/**
 * @brief 开启adc设备 (常规模式)
 * 
 * @param  adcx             : xxx
 * 
 * @return int 
 */
int drv_adc_start(adcNumber_e adcx)
{
    ADC_HandleTypeDef * handle;

    handle = get_adc_handle(adcx);
    if(handle == NULL)
    {
        return DRV_ERROR;
    }    

    HAL_ADC_Start(handle);

    return DRV_EOK;
}


/**
 * @brief 从常规信道的数据寄存器获取转换值
 * 
 * @param  adcx             : xxx
 * 
 * @return uint16_t  返回最近一次ADC1规则组的转换结果
 */
uint16_t drv_adc_get_value(adcNumber_e adcx)
{
    ADC_HandleTypeDef * handle;

    handle = get_adc_handle(adcx);
    if(handle == NULL)
    {
        return DRV_ERROR;
    }    

    return (uint16_t)HAL_ADC_GetValue(handle);    
}


/**
 * @brief DMA方式获取数据 
 * 
 * @param  adcx             : adcx
 * @param  pdata            : 数据存储
 * @param  size             : 从ADC外设传输到存储器的数据长度
 * 
 */
int drv_adc_start_dma(adcNumber_e adcx, uint32_t* pdata, uint16_t size)
{
    ADC_HandleTypeDef * handle;

    handle = get_adc_handle(adcx);
    if(handle == NULL)
    {
        return DRV_ERROR;
    }    

    HAL_ADC_Start_DMA(handle, pdata, size);
	
	return DRV_EOK;
}


#endif /* USE_ADC_DRIVER */
